import { onUnmounted, ref } from 'vue'
import { throttle } from 'lodash-es'

/**
 * 封装 uni.onLocationChange 的钩子函数，带节流处理
 * @param callback 位置变化回调函数
 * @param options 配置选项
 * @param options.throttleTime 节流时间（毫秒），默认 1000
 * @param options.highAccuracy 是否高精度定位，默认 false
 * @param options.provider 位置服务提供商，默认 'system'
 */
export function useLocationChange(
  callback: (location: UniApp.OnLocationChangeCallbackResult) => void,
  options: {
    throttleTime?: number
    highAccuracy?: boolean
    provider?: 'system' | 'baidu' | 'amap'
  } = {}
) {
  const { throttleTime = 1000, highAccuracy = false, provider = 'system' } = options

  // 存储当前位置信息
  const currentLocation = ref<UniApp.OnLocationChangeCallbackResult | null>(null)
  
  // 节流处理后的回调函数
  const throttledCallback = throttle((res: UniApp.OnLocationChangeCallbackResult) => {
    currentLocation.value = res
    callback(res)
  }, throttleTime)

  // 开始监听位置变化
  const startListen = () => {
    uni.onLocationChange((res) => {
      throttledCallback(res)
    })
    wx.startLocationUpdate()
    
    // 如果需要高精度定位，先调用一次获取当前位置
    if (highAccuracy) {
      uni.getLocation({
        type: 'wgs84',
        altitude: true,
        isHighAccuracy: true,
        highAccuracyExpireTime: 5000,
        success: (res) => {
          currentLocation.value = res
          callback(res)
        },
        fail: (err) => {
          console.error('获取高精度位置失败:', err)
        }
      })
    }
  }

  // 停止监听位置变化
  const stopListen = () => {
    uni.offLocationChange(() => {})
    throttledCallback.cancel()
    wx.stopLocationUpdate();
  }

  // 组件卸载时自动停止监听
  onUnmounted(() => {
    stopListen()
  })

  return {
    currentLocation,
    startListen,
    stopListen
  }
}